package com.x.erp.manage;

import com.x.erp.model.ShareCar;
import com.x.erp.model.ShareTemplate;
import com.x.framework.manage.BaseManage;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ShareTemplateManage extends BaseManage {

	/**
	 * 增加分享模板信息
	 * @param shareTemplate
	 * @return
	 */
	public ShareTemplate insertShareTemplate(ShareTemplate shareTemplate) throws Exception {
		shareTemplate.setShareCreateTime(new Date());
		String[] carIds = shareTemplate.getCarIds();
		shareTemplate = this.insert(shareTemplate);
		insertCars(carIds, shareTemplate.getShareId());
		return shareTemplate;
	}

	/**
	 * 删除车辆列表分享模板信息
	 * @param shareTemplate
	 * @return
	 */
	public int deleteShareTemplate(ShareTemplate shareTemplate) throws Exception {
		ShareCar tempShareCar = new ShareCar();
		tempShareCar.setShareId(shareTemplate.getShareId());
		// 删除分享车辆信息
		this.delete(tempShareCar);
		// 删除分享模板信息
		int res = this.delete(shareTemplate);
		return res;
	}
	/**
	 * 修改车辆列表分享模板信息
	 * @param shareTemplate
	 * @return
	 */
	public int updateShareTemplate(ShareTemplate shareTemplate) throws Exception {
		int res = this.update(shareTemplate);
		String[] carIds = shareTemplate.getCarIds();
		insertCars(carIds, shareTemplate.getShareId());
		return res;
	}

	private void insertCars(String[] carIds, String shareId)throws Exception {
		ShareCar temShareCar = null;
		if(shareId != null && carIds != null && carIds.length > 0){
			int seq = 1;
			for (String carId : carIds) {
				temShareCar = new ShareCar();
				temShareCar.setShareId(shareId);
				temShareCar.setCarId(carId);
				temShareCar.setShareSeq(seq++);
				this.insert(temShareCar);
			}
		}
	}
}
